package com.jstyle.jclifexd.activity;

import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.ble.BleManager;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.HealthDataUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.TipsDialog;

import java.text.NumberFormat;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class WorkOutActivity extends BaseActivity {

    @BindView(R.id.bt_workout_cal)
    Button btWorkoutCal;
    @BindView(R.id.bt_workout_time)
    Button btWorkoutTime;
    @BindView(R.id.bt_workout_hr)
    Button btWorkoutHr;
    @BindView(R.id.iv_workout_off)
    ImageView ivWorkoutOff;
    @BindView(R.id.iv_workout_setting)
    ImageView ivWorkoutSetting;
    @BindString(R.string.yoga_cal_laber)
    String yogaCalLabel;
    @BindString(R.string.yoga_hr_laber)
    String yogaHrLabel;
    @BindString(R.string.yoga_time_label)
    String yogaTimeLabel;
    @BindString(R.string.yoga_time_label2)
    String yogaTimeLabel2;
    Disposable disposableTimer;
    public static final String KEY_WORKOUT_TIME = "KEY_WORKOUT_TIME";//单位小时
    public static final String KEY_WORKOUT_CAL = "KEY_WORKOUT_CAL";
    @BindView(R.id.GymCircleProgress)
    com.jstyle.jclifexd.view.GymCircleProgress GymCircleProgress;
    @BindView(R.id.tv_cal)
    TextView tvCal;
    @BindView(R.id.tv_cal_progress)
    TextView tvCalProgress;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_time_progress)
    TextView tvTimeProgress;
    @BindView(R.id.tv_hr_level)
    TextView tvHrLevel;
    private NumberFormat numberFormat;
    @BindArray(R.array.heartRange_array)
    String[] heartArray;
    @BindArray(R.array.hr_color1810_arrays)
    int[] hrColorArrays;
    private TipsDialog tipsDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_out);
        ButterKnife.bind(this);
        setHiddenBack(true);
        numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMaximumFractionDigits(0);
        startTimer();
    }

    @OnClick({R.id.iv_workout_off, R.id.iv_workout_setting})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_workout_off:
                showTipsDialog();
                break;
            case R.id.iv_workout_setting:
                startActivity(WorkOutSettingActivity.class);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        enableMode(false);
        unSubscribe(disposableTimer);
    }

    private void showTipsDialog() {
        if (tipsDialog == null) {
            tipsDialog = new TipsDialog(this, R.style.jstyleDialog_style);
            tipsDialog.setTitle(getString(R.string.Attention));
            tipsDialog.setContent(getString(R.string.Attention_gym_tips));
            tipsDialog.setConfimText(getString(R.string.ok));
            tipsDialog.setTipsConfimListener(new TipsDialog.TipsConfimListener() {
                @Override
                public void onConfim() {
                    enableMode(false);
                    finish();
                }
            });
        }
        tipsDialog.show();
    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState) {
            case ACTIVITY_EXERCISE_DATA:
                String heart = maps.get(DeviceKey.KExerciseHeart);
                String cal = maps.get(DeviceKey.KExerciseCal);
                String time = maps.get(DeviceKey.KExerciseTime);
                if (Float.valueOf(heart) == 255) {
                    finish();
                    return;
                }
                showCalData(Float.valueOf(cal));
                showHrData(Integer.valueOf(heart));
                btWorkoutCal.setText(getKcalSpannable(cal + yogaCalLabel, yogaCalLabel));
                btWorkoutHr.setText(getKcalSpannable(heart + yogaHrLabel, yogaHrLabel));
                long aLong = Long.valueOf(time);
                String label = aLong > 3600 ? yogaTimeLabel2 : yogaTimeLabel;
                showTimeData(Integer.valueOf(time));
                btWorkoutTime.setText(getKcalSpannable(DateUtil.getSportAxieTime(Integer.valueOf(time)) + label, label));
                break;
        }
    }

    private Spannable getKcalSpannable(String text, String label) {
        String startText = label;
        int start = text.indexOf(startText);
        int end = start + startText.length();
        Spannable kcalSpannable = new SpannableString(text);
        setSizeSpannable(kcalSpannable, start, end, 15);
        return kcalSpannable;
    }

    private void setSizeSpannable(Spannable word, int start, int end, int textSize) {
        word.setSpan(new AbsoluteSizeSpan(textSize, true), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }

    public void startTimer() {
        if (disposableTimer != null && !disposableTimer.isDisposed()) return;

        Observable.interval(5, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposableTimer = d;
            }

            @Override
            public void onNext(Long aLong) {
                BleManager.getInstance().writeValue(SingleDealData.sendHeartPackage(0, 0, 0));

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void enableMode(boolean enable) {
        ExerciseMode exerciseMode = new ExerciseMode();
        exerciseMode.setEnableStatus(enable ? ExerciseMode.Status_START : ExerciseMode.Status_FINISH);
        exerciseMode.setExerciseMode(ExerciseMode.Mode_BREATH);
        sendData(SendCmdState.Set_EXERCISE_MODE, exerciseMode);
    }

    private void showCalData(float cal) {
        float calGoal = SharedPreferenceUtils.getFloat(KEY_WORKOUT_CAL, 180);
        float calProgress = cal / calGoal;
        String calPercent = numberFormat.format(calProgress);
        GymCircleProgress.setProgressCal(calProgress);
        tvCalProgress.setText(calPercent);
    }


    private void showHrData(int hr) {
        int maxHr = HealthDataUtils.getMaxHr();
        float hrProgress = Float.valueOf(hr) / maxHr;
        GymCircleProgress.setProgressHeart(hrProgress);
        int hrLevel = HealthDataUtils.getHeartRange(hr);
        tvHrLevel.setTextColor(hrColorArrays[hrLevel]);
        tvHrLevel.setText(heartArray[hrLevel]);
    }

    private void showTimeData(int time) {
        int timeGoal = SharedPreferenceUtils.getInteger(KEY_WORKOUT_TIME, 1);
        float timeProgress = time / (timeGoal * 3600f);
        String timePercent = numberFormat.format(timeProgress);
        GymCircleProgress.setProgressTime(timeProgress);
        tvTimeProgress.setText(timePercent);
    }
}
